package cn.gson.crm.controller.teaching;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ProjectDao;
import cn.gson.crm.model.dao.ProjectLeaderDao;
import cn.gson.crm.model.dao.ProjectPlanDao;
import cn.gson.crm.model.dao.ProjectResourceDao;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.JyInterViewData;
import cn.gson.crm.model.entity.Payrecord;
import cn.gson.crm.model.entity.Project;
import cn.gson.crm.model.entity.ProjectLeader;
import cn.gson.crm.model.entity.ProjectPlan;
import cn.gson.crm.model.entity.ProjectResource;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.mapper.ProjectMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("")
@Log4j
public class FromProjectController {

	@Autowired
	private ProjectPlanDao planDao;
	
	@Autowired
	private ProjectDao projectDao;
	
	@Autowired
	private ProjectLeaderDao leaderDao;
	
	@Autowired
	private ProjectResourceDao resourceDao;
	
	@Autowired
	private ProjectMapper projectMapper;
	/**
	 * 保存项目计划
	 * @param stuinfor
	 * @param br
	 * @return
	 */
	@PostMapping("save")
	@ResponseBody
	public void save(@Valid ProjectPlan plans, BindingResult br,HttpSession session,HttpServletRequest request,HttpServletResponse response) 
					throws Exception{
		Calendar cal=Calendar.getInstance(); 
		User user = (User) session.getAttribute("user");
		Student student = user.getStudent();
		String[] contents=request.getParameterValues("planContent");
		String[] support=request.getParameterValues("support");
		String[] startTime=request.getParameterValues("startTime");
		String[] endTime=request.getParameterValues("endTime");
		String[] finish=request.getParameterValues("finish");
		Long pid=Long.valueOf(request.getParameter("pid"));
		ProjectLeader pl=leaderDao.findOne(pid);
		Project project=pl.getProject();
		String[] ids=request.getParameterValues("id");
			if(ids!=null) {
				if(ids.length>0) {						
					//编辑
					for(int i=0;i<contents.length;i++) {
						//通过id查询计划
						ProjectPlan plan=planDao.findOne(Long.parseLong(ids[i]));
						plan.setPlanContent(contents[i]);
						plan.setSupport(support[i]);
						plan.setStartTime(startTime[i]);
						plan.setEndTime(endTime[i]);
						plan.setFinish(finish[i]);
						planDao.save(plan);				
					}
				}
			}else {
				//添加
				for(int i=0;i<contents.length;i++) {
					ProjectPlan plan=new ProjectPlan();
					plan.setPlanContent(contents[i]);
					plan.setSupport(support[i]);
					plan.setStartTime(startTime[i]);
					plan.setEndTime(endTime[i]);
					plan.setFinish(finish[i]);
					plan.setStudent(student);
					plan.setDeleted(true);
					plan.setProject(project);
					cal.setTime(new Date());
					int num = cal.get(Calendar.WEEK_OF_YEAR);
					int year=cal.getWeekYear();
					plan.setBuildTime(year+"年"+"第"+num+"周");
					planDao.save(plan);				
				}
			}
		request.getRequestDispatcher("right_program_list").forward(request, response);
	}	
	
	/**
	 * 根据项目计划id查询项目计划
	 */
	@RequestMapping("list/{id}")
	public String addproject(Classes cla,@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
				ProjectPlan plan=planDao.findOne(id);
				if(plan!=null) {
					model.addAttribute("plan", plan);
				}
		}	
		return "";
	}
	
	@Value("${upload.file}")
	private String uploadDir;
	/**
	 * 保存项目资料
	 * @param stuinfor
	 * @param br
	 * @return
	 */
	@PostMapping("saveResource")
	@ResponseBody
	public  Map<String,Object>  saveResource(
			@Valid ProjectResource resources, 
			BindingResult br,HttpSession session,
			HttpServletRequest request,
			HttpServletResponse response,@RequestParam(defaultValue="public") String filetype,
			@RequestParam("file") MultipartFile file) 
					throws Exception{
		Map<String,Object> obj = new HashMap<String, Object>();
		//设置路径
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String dateDir = sdf.format(new Date());
		String filePath = String .format("%s/%s/%s", uploadDir,filetype,dateDir);
		File fileDir = new File(filePath);
		if(!fileDir.exists()){
			// 如果目录不存在，则创建出来
			fileDir.mkdirs();
		}
		
		ProjectResource resource=new ProjectResource();
		User user = (User) session.getAttribute("user");
		Student student = user.getStudent();
		String address=request.getParameter("address");
		String uploadTime=request.getParameter("uploadTime");
		String types=request.getParameter("type");
		String proID=request.getParameter("project");
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		String newFileName = UUID.randomUUID().toString()+"."+ext;
		Long id=Long.valueOf(proID);
		Project project=projectDao.findOne(id);
		resource.setProject(project);
		resource.setAddress(address);
		//文件
		resource.setPath(String.format("%s/%s/%s", filetype, dateDir, newFileName));
		resource.setModeType(filetype);
		resource.setSize(file.getSize());
		resource.setContent(fileDir.getPath());
		resource.setMediaName(file.getOriginalFilename());
		resource.setType(types);
		resource.setUploadTime(uploadTime);
		resource.setDeleted(true);
		resource.setStudent(student);
		resourceDao.save(resource);
		obj.put("success", true);
		file.transferTo(new File(fileDir, newFileName));
		return obj;
		
	}	
	
	/**
	 * 查看项目资料
	 */
	@RequestMapping("resourcelist/{pid}")
	@Transactional
	@ResponseBody
	public  Map<String,Object>  index(@PathVariable("pid") Long pid, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		Map<String,Object> obj = new HashMap<String, Object>();
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<ProjectResource> resources = projectMapper.findAllProjectResource(pid);
		PageInfo<ProjectResource> info = new PageInfo<>(resources);
		// 组装返回结果		
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 下载项目资料
	 */
	@RequestMapping("download/{id}")
	@ResponseBody
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id)
			throws IOException {
		// 根据id获取附件信息
		ProjectResource resource = resourceDao.findOne(id);
		if (id == null) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}
		response.setContentLengthLong(resource.getSize());
		response.setContentType(resource.getModeType());
		// 设置附件存储的默认文件名
		String fName  = resource.getMediaName();
		String name=fName +"."+resource.getModeType();
		String  fileName = new String(name.getBytes(), "ISO-8859-1");
		System.out.println(name);
		response.setHeader("Content-Disposition",
				"attachment;filename="+fileName);
		String path =uploadDir+resource.getPath();
		System.out.println("数据库路径："+path);
		ServletOutputStream os = response.getOutputStream();
		// 创建一个输入流
		FileInputStream fis = new FileInputStream(path);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}
		fis.close();

	}
}
